import React, { useState } from "react";
import { Service } from "../api/services/Service";
import type { VidUser_ } from "../api/models/VidUser_";
import "./MobileLogin.css";

interface MobileLoginProps {
  onLoginSuccess: (user: VidUser_) => void;
  onClose: () => void;
  isModal?: boolean; // 是否为弹窗模式，默认true
}

const MobileLogin: React.FC<MobileLoginProps> = ({
  onLoginSuccess,
  onClose,
  isModal = true,
}) => {
  const [isLogin, setIsLogin] = useState(true);
  const [phoneNumber, setPhoneNumber] = useState("");
  const [nickname, setNickname] = useState("");
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState("");

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setError("");

    if (!phoneNumber.trim()) {
      setError("请输入手机号");
      return;
    }

    if (!nickname.trim()) {
      setError("请输入昵称");
      return;
    }

    // 简单的手机号验证
    const phoneRegex = /^1[3-9]\d{9}$/;
    if (!phoneRegex.test(phoneNumber)) {
      setError("请输入正确的手机号");
      return;
    }

    setLoading(true);

    try {
      const userData: VidUser_ = {
        phoneNumber,
        nickName: nickname,
      };

      const response = await Service.loginUsingPost1(userData);

      if (response.data) {
        // 保存用户信息到localStorage
        localStorage.setItem("userInfo", JSON.stringify(response.data));
        localStorage.setItem("isLoggedIn", "true");

        onLoginSuccess(response.data);
      } else {
        setError(isLogin ? response.message : "注册失败，请重试");
      }
    } catch (error: any) {
      console.error("登录/注册失败:", error);
      setError(
        error.response?.data?.message || (isLogin ? "登录失败" : "注册失败")
      );
    } finally {
      setLoading(false);
    }
  };

  const renderContent = () => (
    <div className="mobile-login-container">
      <div className="login-header">
        <div className="app-icon">
          <svg width="40" height="40" viewBox="0 0 24 24" fill="#4a90e2">
            <path d="M17 10.5V7a1 1 0 00-1-1H4a1 1 0 00-1 1v10a1 1 0 001 1h12a1 1 0 001-1v-3.5l4 4v-11l-4 4z" />
          </svg>
        </div>
        <h1>你好,</h1>
        <p>欢迎来到小叔观影的历史站</p>
      </div>

      <form onSubmit={handleSubmit} className="login-form">
        <div className="input-group">
          <input
            type="tel"
            placeholder="请输入手机号"
            value={phoneNumber}
            onChange={(e) => setPhoneNumber(e.target.value)}
            className="form-input"
            maxLength={11}
          />
        </div>

        <div className="input-group">
          <input
            type="text"
            placeholder="昵称"
            value={nickname}
            onChange={(e) => setNickname(e.target.value)}
            className="form-input"
            maxLength={20}
          />
          <p style={{ color: "gray", fontSize: 12, marginTop: 8 }}>
            请输入您视频注册平台的昵称 !
          </p>
        </div>

        {error && <div className="error-message">{error}</div>}

        <button type="submit" className="submit-button" disabled={loading}>
          登录/注册
        </button>
      </form>
    </div>
  );

  if (isModal) {
    return <div className="mobile-login-overlay">{renderContent()}</div>;
  }

  return <div className="mobile-login-page">{renderContent()}</div>;
};

export default MobileLogin;
